package com.magima.core.basic.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectionUtil {
	public static String getId(Object obj, Class<?> typeOfT, String idAttribute) {
		Field field = null;
		String id = "";
		try {
			field = typeOfT.getField(idAttribute);
		} catch (NoSuchFieldException e) {
			try {
				field = typeOfT.getDeclaredField(idAttribute);
				field.setAccessible(true);
			} catch (NoSuchFieldException e2) {
			}
		}
		try {
			if (field != null) {				
				id = String.valueOf(field.get(obj));
			} else {
				Method method = null;
				try {
					method = typeOfT.getMethod(idAttribute);
				} catch (NoSuchMethodException e) {
					try {
						method = typeOfT.getDeclaredMethod(idAttribute);
						method.setAccessible(true);
					} catch (NoSuchMethodException e2) {
					}
				}
				if ( method != null ) {					
					id = String.valueOf(method.invoke(obj, (Object[]) null));
				}
			}
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}

		return id;
	}
	
	public static Object getField(Object obj, Class<?> typeOfT, String fieldName){
		Field field = null;
		Object retObj = null;
		try {
			field = typeOfT.getField(fieldName);
		} catch (NoSuchFieldException e) {
			try {
				field = typeOfT.getDeclaredField(fieldName);
				field.setAccessible(true);
			} catch (NoSuchFieldException e2) {
			}
		}
		try {
			if (field != null) {
				retObj = field.get(obj);
			} else {
				return null;
			}
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}

		return retObj;
	}
	
	public static void setField(Object obj, Class<?> typeOfT, String fieldName, Object fieldValue){
		Field field = null;
		try {
			field = typeOfT.getField(fieldName);
		} catch (NoSuchFieldException e) {
			try {
				field = typeOfT.getDeclaredField(fieldName);
				field.setAccessible(true);
			} catch (NoSuchFieldException e2) {
			}
		} 
		try {
			if (field != null) {
				field.set(obj, fieldValue);
			} else
				return;
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}
}
